from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import json


class Environment(models.Model):
    """环境配置模型"""
    name = models.CharField(max_length=100, verbose_name='环境名称')
    base_url = models.CharField(max_length=500, verbose_name='基础URL')
    description = models.TextField(blank=True, verbose_name='环境描述')
    yaml_config = models.TextField(blank=True, verbose_name='YAML配置文件')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '环境配置'
        verbose_name_plural = '环境配置'

    def __str__(self):
        return self.name


class TestCase(models.Model):
    """测试用例模型"""
    CASE_TYPE_CHOICES = [
        ('single', '单接口测试'),
        ('scenario', '场景测试'),
    ]

    name = models.CharField(max_length=200, verbose_name='用例名称')
    description = models.TextField(blank=True, verbose_name='用例描述')
    case_type = models.CharField(max_length=20, choices=CASE_TYPE_CHOICES, verbose_name='用例类型')
    yaml_content = models.TextField(verbose_name='YAML配置内容')
    environment = models.ForeignKey(Environment, on_delete=models.CASCADE, verbose_name='测试环境')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建者')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '测试用例'
        verbose_name_plural = '测试用例'

    def __str__(self):
        return self.name


class TestExecution(models.Model):
    """测试执行记录模型"""
    STATUS_CHOICES = [
        ('pending', '待执行'),
        ('running', '执行中'),
        ('passed', '通过'),
        ('failed', '失败'),
        ('error', '错误'),
    ]

    test_case = models.ForeignKey(TestCase, on_delete=models.CASCADE, verbose_name='测试用例')
    environment = models.ForeignKey(Environment, on_delete=models.CASCADE, verbose_name='执行环境')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='执行状态')
    result = models.JSONField(default=dict, verbose_name='执行结果')
    error_message = models.TextField(blank=True, verbose_name='错误信息')
    execution_time = models.FloatField(null=True, blank=True, verbose_name='执行时长(秒)')
    started_at = models.DateTimeField(null=True, blank=True, verbose_name='开始时间')
    finished_at = models.DateTimeField(null=True, blank=True, verbose_name='结束时间')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='执行者')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '测试执行记录'
        verbose_name_plural = '测试执行记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.test_case.name} - {self.get_status_display()}"


class TestReport(models.Model):
    """测试报告模型"""
    name = models.CharField(max_length=200, verbose_name='报告名称')
    description = models.TextField(blank=True, verbose_name='报告描述')
    total_cases = models.IntegerField(default=0, verbose_name='总用例数')
    passed_cases = models.IntegerField(default=0, verbose_name='通过用例数')
    failed_cases = models.IntegerField(default=0, verbose_name='失败用例数')
    error_cases = models.IntegerField(default=0, verbose_name='错误用例数')
    success_rate = models.FloatField(default=0.0, verbose_name='成功率')
    execution_details = models.JSONField(default=dict, verbose_name='执行详情')
    report_file = models.FileField(upload_to='reports/', blank=True, verbose_name='报告文件')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建者')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '测试报告'
        verbose_name_plural = '测试报告'
        ordering = ['-created_at']

    def __str__(self):
        return self.name

    def calculate_success_rate(self):
        """计算成功率"""
        if self.total_cases > 0:
            self.success_rate = (self.passed_cases / self.total_cases) * 100
        return self.success_rate 


class DailyLog(models.Model):
    name = models.CharField(max_length=255, verbose_name="需求标题")
    tester = models.CharField(max_length=100, blank=True, null=True, verbose_name="测试人员")
    demand_time = models.CharField(max_length=100, blank=True, null=True, verbose_name="需求规模")
    version = models.CharField(max_length=100, blank=True, null=True, verbose_name="项目")
    module = models.CharField(max_length=100, blank=True, null=True, verbose_name="模块")
    product = models.CharField(max_length=100, blank=True, null=True, verbose_name="产品经理")
    review_time = models.DateField(blank=True, null=True, verbose_name="评审时间")
    status = models.CharField(max_length=100, blank=True, null=True, verbose_name="需求状态")
    test_time = models.CharField(max_length=100, blank=True, null=True, verbose_name="测试工时")
    test_date = models.DateField(blank=True, null=True, verbose_name="提测日期")
    launch_time = models.DateField(blank=True, null=True, verbose_name="上线日期")
    log_content = models.TextField(blank=True, null=True, verbose_name="日志内容")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True) 